package org.web.ssm.controller.wechatController;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.web.ssm.dto.ResultModel;
import org.web.ssm.dto.Shoppinglist;
import org.web.ssm.exception.ShoppingException;
import org.web.ssm.model.Shopping;
import org.web.ssm.model.User;
import org.web.ssm.service.wechatService.IShoppingService;
import org.web.ssm.utils.JsonUtil;

import java.util.Date;

/**
 * Created by LUOLIANG on 2016/6/18.
 */
@RestController
@RequestMapping("/Shopping")
@SessionAttributes("currUser")
public class ShoppingController {
    @Autowired
    private IShoppingService shoppingService;

    @RequestMapping(value = "/shoppinglist", method = RequestMethod.POST)
    public String shoppinglist(@ModelAttribute("currUser") User user) {
        Shoppinglist shoppinglist = shoppingService.getListBytype(user.getUserid());

        return JsonUtil.toJson("yyyy-MM-dd", new ResultModel<Shoppinglist>(true, shoppinglist));
    }

    @RequestMapping(value = "/addShopping", method = RequestMethod.POST)
    public String addShopping(@ModelAttribute("currUser") User user, @RequestParam("content") String content) {
        Shopping shopping = new Shopping(content, new Date(), false, user);

        try {
            shoppingService.insertShopping(shopping);
            return JSON.toJSONString(new ResultModel<Shopping>("添加成功", true));
        } catch (Exception e) {
            throw new ShoppingException(e.getMessage());
        }
    }

    @RequestMapping(value = "/updateShopping", method = RequestMethod.POST)
    public String updateShopping(@RequestParam("id") String id) {
        try {
            shoppingService.updateShopping(id);
            return JSON.toJSONString(new ResultModel<Shopping>("更新成功", true));
        } catch (Exception e) {
            throw new ShoppingException(e.getMessage());
        }
    }

    @RequestMapping(value = "/delShopping", method = RequestMethod.POST)
    public String delShopping(@RequestParam("id") String id) {
        try {
            shoppingService.deleteShoppping(id);
            return JSON.toJSONString(new ResultModel<Shopping>("删除成功", true));
        } catch (Exception e) {
            throw new ShoppingException(e.getMessage());
        }
    }
}
